<template>
    <div class="son">
        儿子，家庭总资产为{{ assets }}元
        <el-button style="margin-left: 2rem" @click="makeMoney(3)">赚钱</el-button>
        <el-button @click="spendMoney(3)">花钱</el-button>
    </div>
</template>

<script lang="ts">
import { defineComponent, inject } from 'vue';

export default defineComponent({
    name: 'Son',
    setup() {
        // 注入总资产和更新方法
        const assets = inject<number>('assets')!;
        const updateAssets = inject<(newAssets: number) => void>('updateAssets')!;

        // 赚钱
        const makeMoney = (money: number) => {
            assets.value += money;
            updateAssets(assets.value);
            console.log(`儿子赚了${money}元，总资产变为${assets.value}元`);
        };

        // 花钱
        const spendMoney = (money: number) => {
            if (assets.value >= money) {
                assets.value -= money;
                updateAssets(assets.value);
                console.log(`儿子花了${money}元，总资产变为${assets.value}元`);
            } else {
                console.error('家庭总资产不足');
            }
        };

        return {
            assets,
            makeMoney,
            spendMoney
        };
    }
});

</script>

<style lang='scss' scoped>
.son {
    width: 30vw;
    height: 8rem;
    border: 1px solid #000;
    border-radius: 5px;
    padding: 2rem;
    margin: 2rem;
}
</style>